/*
* JBoss, Home of Professional Open Source
* Copyright 2006, JBoss Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package si.ibloc.cms.logic.impl;

import java.util.Date;
import javax.ejb.Remove;
import javax.ejb.Stateful;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.hibernate.search.FullTextSession;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Create;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.Startup;
import si.ibloc.cms.logic.interfaces.Indexer;
import si.ibloc.cms.model.Article;
import si.ibloc.cms.model.File;

/**
 * @author <a href="mailto:ales.justin@jboss.com">Ales Justin</a>
 */
@Name("indexer")
@Stateful
@Scope(ScopeType.APPLICATION)
@Startup
public class IndexerAction implements Indexer {
   private Date lastIndexingTime;
   @PersistenceContext
   private transient EntityManager em;

   public Date getLastIndexingTime() {
      return lastIndexingTime;
   }

   @Create
   public void index() {
      indexAllClasses(
            Article.class,
            File.class
      );
      lastIndexingTime = new Date();
   }

   protected FullTextSession getFullTextSession() {
      return (FullTextSession)em.getDelegate();
   }

   protected void indexAllClasses(Class... entityTypes) {
      FullTextSession fullTextSession = getFullTextSession();
      for (Class entityType : entityTypes) {
         for (Object obj : fullTextSession.createCriteria(entityType).list()) {
            fullTextSession.index(obj);
         }
      }
   }

   @Remove
   public void stop() {}

}
